﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Xml;
using ServiceStack.Redis;


namespace CloudPms.Common.CacheProvider
{
    public class RedisStore<T> where T:new()
    {
        private static volatile RedisStore<T> _instance;
        private static readonly object _locker = new object();
        private static volatile PooledRedisClientManager _poolManager;
     

        private RedisStore()
        {
        }

        public static RedisStore<T> GetInstance()
        {
            if(_instance==null)
            {
                lock(_locker)
                {
                    if(_instance==null)
                    {
                        _poolManager = PooledManager.Instance.GetPooledClientManager();
                        _instance = new RedisStore<T>();
                    }
                }
            }
            return _instance;
        }
        
        public T Add(string key, T value)
        {
            using (IRedisClient redis = _poolManager.GetClient())
            {
                redis.Set<T>(key, value);
            }
            return value;
        }

        public T Get(string key)
        {
            using (IRedisClient redis = _poolManager.GetReadOnlyClient())
            {
                return redis.Get<T>(key);
            }
        }

        public void Remove(string key)
        {
            using (IRedisClient redis = _poolManager.GetClient())
            {
                redis.Remove(key);
            }
        }

        public void BatchAdd(List<T> items)
        {
            using (IRedisClient redis = _poolManager.GetClient())
            {
                var list = redis.GetTypedClient<T>();
                list.StoreAll(items);
            }
        }

        public IList<T> BatchGet(Expression<Func<T, bool>> exp)
        {
            using (IRedisClient redis = _poolManager.GetReadOnlyClient())
            {
                var list = redis.GetTypedClient<T>();
                return list.GetAll();
            }
        }

        public void BatchRemove(IEnumerable<string> ids)
        {
            using (IRedisClient redis = _poolManager.GetClient())
            {
                var list = redis.GetTypedClient<T>();
                list.DeleteByIds(ids);
            }
        }

    }
}
